package com.example.testwebrtc

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

import org.webrtc.*

import org.webrtc.PeerConnectionFactory.InitializationOptions


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // create PeerConnectionFactory
        // create PeerConnectionFactory
        val initializationOptions = InitializationOptions.builder(this).createInitializationOptions()
        PeerConnectionFactory.initialize(initializationOptions)
        val peerConnectionFactory = PeerConnectionFactory.builder().createPeerConnectionFactory()

        // create AudioSource

        // create AudioSource
        val audioSource: AudioSource = peerConnectionFactory.createAudioSource(MediaConstraints())
        val audioTrack: AudioTrack = peerConnectionFactory.createAudioTrack("101", audioSource)

        val eglBaseContext = EglBase.create().eglBaseContext

        val surfaceTextureHelper = SurfaceTextureHelper.create("CaptureThread", eglBaseContext)
        // create VideoCapturer
        // create VideoCapturer
        val videoCapturer: VideoCapturer? = createCameraCapturer()
        val videoSource: VideoSource = peerConnectionFactory.createVideoSource(videoCapturer!!.isScreencast)
        videoCapturer?.initialize(surfaceTextureHelper, applicationContext, videoSource.getCapturerObserver())
        videoCapturer?.startCapture(480, 640, 30)

        val localView = findViewById<SurfaceViewRenderer>(R.id.local_view)
        localView.setMirror(true)
        localView.init(eglBaseContext, null)
        Log.d("ansion","test0")
        // create VideoTrack

        // create VideoTrack
        val videoTrack = peerConnectionFactory.createVideoTrack("101", videoSource)
        // display in localView
        // display in localView
        videoTrack.addSink(localView)
    }
     fun  createCameraCapturer():VideoCapturer? {
        val enumerator = Camera1Enumerator(false)
        val deviceNames = enumerator.deviceNames

        // First, try to find front facing camera

        // First, try to find front facing camera
        for (deviceName in deviceNames) {
            if (enumerator.isFrontFacing(deviceName)) {
                val videoCapturer: VideoCapturer? = enumerator.createCapturer(deviceName, null)
                if (videoCapturer != null) {
                    return videoCapturer
                }
            }
        }

        // Front facing camera not found, try something else
        for (deviceName in deviceNames) {
            if (!enumerator.isFrontFacing(deviceName)) {
                val videoCapturer: VideoCapturer? = enumerator.createCapturer(deviceName, null)
                if (videoCapturer != null) {
                    return videoCapturer
                }
            }
        }

        return null
    }

}